//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

#include <aura.h>

#define MY_CHANNEL "MyCentral"
#define BUFSIZE 4096

EXTERN_C void AnsiToUnic(
            /* [out] */ Aura_PWChar desc,
            /* [in] */ char *src)
{
    while (*src) {
        *desc++ = (Aura_WChar)*src++;
    }
    *desc = 0;
}

static void* MyRequestRoutine(Aura_PVoid arg)
{
    Aura_ECode ec;
    Aura_ChannelId channelId;

    char info[BUFSIZE];

    channelId = (Aura_ChannelId)arg;
    printf("Request Thread id:%d\n", pthread_self());

    while (1) {
        // Read the request from client
        ec = AuraIpcChannel_Read(channelId, info, BUFSIZE);
        if (AURA_FAILED(ec))
            goto Exit;

        if(0 == info[0]){
            //End
            break;
        }
        // TODO:PROCESS THE REQUEST
        printf(">>>Receive Message: %s\n", info);
        sprintf(info, "%s from server", info);
        printf("<<<Send Message: %s\n", info);

        // Send the reply to client
        ec = AuraIpcChannel_AsyncWrite(channelId, info, BUFSIZE);
        if (AURA_FAILED(ec)) {
            goto Exit;
        }
    }

Exit:
    printf("MyRequestRoutine Exit ec:%d\n", ec);
    return NULL;
}

Aura_ECode central_request_loop(void)
{
    Aura_ChannelId channelId, listenedId;
    Aura_ECode ec = AURA_NOERROR;
    pthread_t tid;
    Aura_WChar wtmp[64];

    AnsiToUnic(wtmp,MY_CHANNEL);
    ec = AuraIpcChannel_Create(wtmp, &listenedId);
    if (AURA_FAILED(ec)) {
        goto Exit;
    }

    do {
        ec = AuraIpcChannel_WaitForConnection(wtmp, &listenedId, &channelId);
        if (AURA_FAILED(ec)) {
            printf("AuraIpcChannel_WaitForConnection Failed\n");
            continue;
        }

        printf("New connection, channelId: %d\n", channelId);

        int err = pthread_create(&tid, NULL, MyRequestRoutine, (Aura_PVoid)channelId);
        if (err != 0) {
            printf("pthread_create fault!\n");
            goto Exit;
        }
    }while ('q' != getchar());

Exit:
    AuraIpcChannel_Destroy(listenedId);
    return ec;
}

int main(void)
{
    central_request_loop();

    return 0;
}
